import { Context } from 'koa';
const { getRoleByIdentity } = require('../service/role.service')
const { identityError, identityExisted, verifyRoleError, identityNotExisted, invalidID } = require('../constants/err.type');

const verifyRole = async(ctx: Context, next: () => Promise<void>) => {
    const { identity } = ctx.request.body;
    try {
        if(identity < 0 || identity > 128 || identity % 2 !== 0) {
            console.error('identity不符合规范，必须是0~128内的二进制数', identity)
            return ctx.app.emit('error', identityError, ctx)
        }
        const res = await getRoleByIdentity(identity)
        if(res) {
            console.error('当前用户的identity已存在', identity)
            return ctx.app.emit('error', identityExisted, ctx)
        }
    } catch (error) {
        console.error(error)
        return ctx.app.emit('error', verifyRoleError, ctx)
    }
    await next()
}
// 判断identity是否存在
const identityExist = async(ctx: Context, next: () => Promise<void>) => {
    const identity = ctx.params.identity
    try {
        const role = await getRoleByIdentity(identity)
        if(!role) {
            return ctx.app.emit('error', identityNotExisted, ctx)
        }
    } catch (error) {
        console.error(error)
        return ctx.app.emit('error', verifyRoleError, ctx)
    }
    await next()
}

module.exports = {
    verifyRole,
    identityExist
}